﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SoufunData.DB;

namespace SoufunData
{
    public partial class ExToDbBBSummarize : DevExpress.XtraEditors.XtraForm
    {
        public ExToDbBBSummarize()
        {
            InitializeComponent();
        }

        private void btn_excelPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;
            btn_excelPath.Text = fileName;

            gridControl2.DataSource = null;
            gridView2.Columns.Clear();
            gridView2.GroupPanelText = "请选择Excel文件";
            if (fileName == "")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds == null || ds.Tables.Count == 0)
            {
                string strError = "读取Excel时发生错误，请核对：\r\n ";
                strError += "1，导入时请在Excel中关闭想要导入的文件！\r\n";
                strError += "2，导入的Excel表中的工作表名称必须为Sheet1,否者程序无法读取！\r\n";
                strError += "3，请确保您的计算机安装了Microsoft Office！\r\n";
                strError += "4，请确保导入的Excel文件正常！";                
                XtraMessageBox.Show(strError);
                btn_excelPath.Text = "";
                return;
            }
            if (!CheckExcelColumnsName(ds.Tables[0]))
            {
                btn_excelPath.Text = "";
                return;
            }
            gridControl2.DataSource = ds.Tables[0];
            gridView2.GroupPanelText = "共有" + ds.Tables[0].Rows.Count + "条数据";
        }


        private void AddData()
        {

            DataTable dtOld = (DataTable) gridControl2.DataSource;

            DataTable dt = dtOld.Copy();
            dt.Rows.Clear();
            foreach (DataRow dataRow in dtOld.Rows)
            {
                dt.Rows.Add(dataRow.ItemArray);
            }

            SqlClass sqlClass = new SqlClass();
            List<string> existProject = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                string proName = row["项目名称"].ToString();
                if (sqlClass.ExistProjectName(proName, "tbsummarize"))
                {
                    existProject.Add(proName);
                }
            }
            if (existProject.Count > 0)
            {
                StringBuilder strWarming = new StringBuilder();
                strWarming.Append("您选择的Excel表格中的以下项目在数据库中已存在,不能再次添加：\r\n");
                foreach (string sproName in existProject)
                {
                    strWarming.Append(sproName);
                    strWarming.Append("\r\n");
                }
                XtraMessageBox.Show(strWarming.ToString());
                BeginInvoke(new MethodInvoker(() =>
                {
                    btn_excelPath.Text = "";
                    gridControl2.DataSource = null;
                    btn_excelPath.Enabled = true;
                    btn_add.Enabled = true;
                }));
                return;
            }



            int insertRowsCount = 500; //一次性插入数据库行数
            int succeedrows = 0; //成功插入数据行数
            StringBuilder strSql = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                string strProName = row["项目名称"].ToString();
                string strFeature = row["项目特色"].ToString();
                string strOrientate = row["项目定位"].ToString();
                string strRange = row["项目辐射范围"].ToString();
                string strAdvantage = row["项目优势"].ToString();
                string strDisadvantage = row["项目劣势"].ToString();

                if (i%insertRowsCount == 0)
                {
                    strSql = new StringBuilder();
                    strSql.Append("Insert into tbsummarize (");
                    strSql.Append("ProjectName,");
                    strSql.Append("Feature,");
                    strSql.Append("Orientate,");
                    strSql.Append("`Range`,");
                    strSql.Append("Advantage,");
                    strSql.Append("Disadvantage)");
                    strSql.Append(" value  ");
                }
                strSql.Append("(");
                strSql.Append("'");
                strSql.Append(strProName);
                strSql.Append("','");
                strSql.Append(strFeature);
                strSql.Append("','");
                strSql.Append(strOrientate);
                strSql.Append("','");
                strSql.Append(strRange);
                strSql.Append("','");
                strSql.Append(strAdvantage);
                strSql.Append("','");
                strSql.Append(strDisadvantage);
                strSql.Append("'),");

                if ((i + 1)%insertRowsCount == 0
                    || i == dt.Rows.Count - 1)
                {
                    strSql.Remove(strSql.Length - 1, 1);
                    try
                    {
                        succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show(ex.Message);
                    }

                }
            }

            if (dt.Rows.Count == succeedrows)
            {
                XtraMessageBox.Show("添加成功！");
                BeginInvoke(new MethodInvoker(() =>
                    {
                        btn_excelPath.Text = "";
                        gridControl2.DataSource = null;
                        gridView2.GroupPanelText = "请选择想要导入的Excel表！";
                    }));
            }
            else
            {
                int failedCount = dt.Rows.Count - succeedrows;
                XtraMessageBox.Show("共记" + dt.Rows.Count + "条数据，其中"
                                    + failedCount + "条数据添加失败！");
            }
            BeginInvoke(new MethodInvoker(() =>
                {

                    btn_excelPath.Enabled = true;
                    btn_add.Enabled = true;
                }));
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (btn_excelPath.Text.Trim() == "")
            {
                XtraMessageBox.Show("请先选择Excel！");
                return;
            }
            if (!CheckDataValid())
            {
                return;
            }

            btn_excelPath.Enabled = false;
            btn_add.Enabled = false;
            Thread t = new Thread(AddData) {IsBackground = true};
            t.Start();
        }

        #region 数据完整性检测

        private bool CheckDataValid()
        {
            DataTable dt = (DataTable) gridControl2.DataSource;
            StringBuilder strErrors = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string strProName = dr["项目名称"].ToString();

                if (strProName.Trim() == "")
                {
                    strErrors.Append("第" + (i + 1) + "行数据中的【项目名称】为空！\r\n");
                }
            }
            if (strErrors.ToString() != "")
            {
                XtraMessageBox.Show("您选择的Excel中的数据存在以下错误：\r\n" +
                                    strErrors);
                return false;
            }
            return true;
        }

        private bool CheckExcelColumnsName(DataTable dt)
        {
            StringBuilder strErrors = new StringBuilder();
            if (!dt.Columns.Contains("项目名称"))
            {
                strErrors.Append("【项目名称】、");
            }
            if (!dt.Columns.Contains("项目特色"))
            {
                strErrors.Append("【项目特色】、");
            }
            if (!dt.Columns.Contains("项目定位"))
            {
                strErrors.Append("【项目定位】、");
            }
            if (!dt.Columns.Contains("项目辐射范围"))
            {
                strErrors.Append("【项目辐射范围】、");
            }
            if (!dt.Columns.Contains("项目优势"))
            {
                strErrors.Append("【项目优势】、");
            }
            if (!dt.Columns.Contains("项目劣势"))
            {
                strErrors.Append("【项目劣势】、");
            }

            if (strErrors.ToString() != "")
                {
                    XtraMessageBox.Show("您选择的Excel表数据不正常,缺少以下数据列:\r\n" +
                                        strErrors);
                    return false;
                }
            return true;
        }
        #endregion
    }
}